<html>
<body>

<h1>
Calculator
</h1>
Type an expression into the following box (e.g., 10.5+20*3/25).

<form action="calculator.php" method="GET">
<input type="text" name="calc"/>
<input type="submit" value="Calculate!" /><br/><br/>

<?php
	// Set GET variable
	$equ = $_GET["calc"];

	// Only evaluate if something was inputted
	if (strlen($equ) > 0) {
		// Regular expression that matches form A (op B)*
		// allowing any number of spaces between num and ops
		preg_match("/([\s]*[\-]?[0-9]+[\.]?[0-9]*[\s]*)([\s]*(([\+\*\/]?[\s]*)|([\-]?[\s]+))[\-]?[0-9]+[\.]?[0-9]*[\s]*)*/", $equ, $matches);

		// Print out the results
		echo "<b>Results:</b><br/>";

		if (strlen($matches[0]) != strlen($equ)) {
			echo "Invalid input expression ".$equ.".<br/>";
		}
		else {
			@eval("\$ans = $equ;");
			echo $equ." = ".$ans."<br/>";
		}
	}
?>

</body>
</html>
